using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using AJAXCore.Repositories;
using AJAXCore.Models;

namespace AJAXCore.Controllers {
  public class ServiceController : Controller {
    private IRepository _repository;

    public ServiceController(IRepository repository) {
      _repository = repository;
    }
    public IActionResult Index() {
      return View();
    }

    public IActionResult Countries() {
      if (_repository.Count<Country>() == 0) return Content("");
      return View(_repository.Countries);
    }

    public IActionResult States(string countryName, string useLocalName = "no") {
      if (_repository.Count<State>() == 0) return Content("");
      var country = _repository.Countries.FirstOrDefault(c => c.Name == countryName);
      if (country == null) return Content("");

      var names = from s in _repository.States
                  where s.Country == country.Code
                  select (useLocalName == "yes") ? (s.LocalName??s.Name) : s.Name;

      if (names.Count() == 0) return Content("");
      return View(names);
    }

    public string CheckUser(string userName) {
      System.Threading.Thread.Sleep(5000);//Intentionally simulate service latency
      var member = _repository.Members.FirstOrDefault(m => m.Name == userName);
      return (member==null)?"":member.Password;
    }

    static bool isLeapYear(int year) {
      if ((year % 4) != 0) return false;
      if ((year % 100) != 0) return true;
      if ((year % 400) != 0) return false;
      return true;
    }

    enum Month { 
      JAN=31, FEB=28, MAR=31, APR=30, May=31, JUN=30,
      JUL=31, AUG=31, SEP=30, OCT=31, NOV=30, DEC=31
    }
    public IActionResult GetDays(int year, string sMonth) {
      Month m = Enum.Parse<Month>(sMonth);
      return View((m==Month.FEB)?(isLeapYear(year)?29:28):(int)m);
    }
  }
}